using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Read.API.Applications.Commands.reportforms;
using SupplierCustomerManagement.Read.API.Dtos.ReportForms;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.reportforms
{
    public class GetProductionTableOverviewQueryHandler : IRequestHandler<GetProductionTableOverviewQuery, List<ProductionTableRowDto>>
    {
        private readonly SupplierDbContext _db;
        private readonly ILogger<GetProductionTableOverviewQueryHandler> _logger;

        public GetProductionTableOverviewQueryHandler(SupplierDbContext db, ILogger<GetProductionTableOverviewQueryHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<List<ProductionTableRowDto>> Handle(GetProductionTableOverviewQuery request, CancellationToken cancellationToken)
        {
            // 计算查询区间
            var period = string.IsNullOrWhiteSpace(request.Period) ? "month" : request.Period.Trim().ToLower();
            DateTime startDate;
            DateTime endDate;
            if (period == "year")
            {
                var year = DateTime.Today.Year;
                startDate = new DateTime(year, 1, 1);
                endDate = new DateTime(year, 12, 31, 23, 59, 59, 999);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(request.Month) && DateTime.TryParse(request.Month + "-01", out var monthDate))
                {
                    startDate = new DateTime(monthDate.Year, monthDate.Month, 1);
                }
                else
                {
                    var today = DateTime.Today;
                    startDate = new DateTime(today.Year, today.Month, 1);
                }
                endDate = startDate.AddMonths(1).AddTicks(-1);
            }

            var query = _db.ProductionSummaries.AsNoTracking()
                .Where(x => x.ReportDate >= startDate && x.ReportDate <= endDate);
            if (request.FarmId.HasValue)
            {
                var farmId = request.FarmId.Value;
                query = query.Where(x => x.FarmId == farmId);
            }

            var agg = await query
                .GroupBy(x => 1)
                .Select(g => new
                {
                    TotalEwes = g.Sum(x => x.TotalEwes) ?? 0,
                    BreedingEwes = g.Sum(x => x.BreedingEwes) ?? 0,
                    PregnantEwes = g.Sum(x => x.PregnantEwes) ?? 0,
                    LambingEwes = g.Sum(x => x.LambingEwes) ?? 0,
                    TotalLambs = g.Sum(x => x.TotalLambs) ?? 0,
                    LiveLambs = g.Sum(x => x.LiveLambs) ?? 0
                })
                .FirstOrDefaultAsync(cancellationToken) ?? new
                {
                    TotalEwes = 0,
                    BreedingEwes = 0,
                    PregnantEwes = 0,
                    LambingEwes = 0,
                    TotalLambs = 0,
                    LiveLambs = 0
                };

            var rows = new List<ProductionTableRowDto>
            {
                new ProductionTableRowDto
                {
                    Category = "配种",
                    // 近似：将配种母羊数视为配种合计
                    TotalMating = agg.BreedingEwes
                },
                new ProductionTableRowDto
                {
                    Category = "分娩",
                    LitterCount = agg.LambingEwes,
                    HealthyLamb = agg.LiveLambs,
                    TotalLiveBirth = agg.LiveLambs,
                    TotalLiveLamb = agg.LiveLambs
                },
                new ProductionTableRowDto
                {
                    Category = "断奶",
                    // 暂无断奶原子字段，保持为0
                },
                new ProductionTableRowDto
                {
                    Category = "存栏变动",
                    Beginning = agg.TotalEwes,
                    Ending = agg.TotalEwes,
                    Lambing = agg.LiveLambs,
                    TotalIn = agg.LiveLambs,
                    TotalOut = 0
                }
            };

            return rows;
        }
    }
}
